<template>
    <pageTabelLayout>
        <template #pageHeader>
            <div class="search-form divClass" v-if="headerShow">
                <div>
                    <a-form size="small " :model="queryData" layout="inline">
                        <a-form-item label="公司">
                            <a-select popup-container="html" class="bacClass" v-model="queryData.firm"
                                :style="{ width: '200px' }" @press-enter="huiche" :loading="loading" :allowClear="true"
                                :filter-option="false" @focus="focusSel1">
                                <a-option v-for="item in pageData.firmList">{{ item.firmName }}</a-option>
                            </a-select>
                        </a-form-item>
                    </a-form>
                </div>
                <div>
                    <Toolbar :items="['查询', '导出']" @select="selectHandler" @export="exportBtn" style="float: right;">
                    </Toolbar>
                </div>
            </div>
            <div class="my-divisders">
                <a-divider orientation="center">
                    <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
                    <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
                </a-divider>
            </div>
        </template>
        <!-- 上部分 -->
        <template #pageTabel>
            <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height:100%;width: 100%;z-index:999 ;">
                <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                    rowSelection="multiple" @grid-ready="gridReady" style="height:calc(100% - 45px)" :defaultColDef="defaultColDef"
                    class='ag-theme-alpine' :rowData="table.dataList" :columnDefs="tc" :localeText="localeText1"
                    @columnResized="onColumnResized" @columnMoved="onColumnMoved"></AgGridVuesCopys>
                <paginationCopys :page-size-options="pagingList1" :total="total" show-total show-jumper show-page-size
                    @change="PageSize" @page-size-change="change1" style="justify-content: center" :page-size="size" :current="page"/>
            </a-spin>
        </template>

        <a-drawer :drawer-style="{ 'zIndex': 999 }" :mask-closable="false" :height="800" :visible="pageData.showAdd"
            @ok="sideOk" @cancel="pageData.showAdd = false" unmountOnClose placement="bottom"
            popup-container=".main-base-style" ok-text="保存" cancel-text="关闭">
            <div>
                <a-tabs   :lazy-load="true" :default-active-key="1">
                    <a-tab-pane title="机器产能设定" :key="1">
                        <div style="min-height: 100px">
                            <!-- 表格 -->
                            <div class="Btn">
                                <a-button type="primary" class="addBtn" @click="addBtn">新增</a-button>
                                <a-button type="primary" class="delBtn" @click="delBtn">删除</a-button>
                            </div>
                            <div style="padding:20px;box-sizing: border-box;">
                                <a-table stripe :columns="columns2" :data="dataList" :bordered="false"
                                    :row-selection="{ showCheckedAll: true, width: 50 }" size="small"
                                    v-model:selected-keys="selectedRowKeys" :column-resizable="true" rowKey="id">
                                    <template #action="{ record }">
                                        <!-- <a-button type="primary" size="mini" status="warning"
                                            @click="record['add'] == undefined ? record['edit'] = true : record['add'] = true">
                                            <template #icon>
                                                <icon-edit />
                                            </template>
                                            修 改
                                        </a-button> -->
                                        <el-button style="color:#165dff;" type="info" link
                                            @click="record['add'] == undefined ? record['edit'] = true : record['add'] = true">修改</el-button>
                                    </template>
                                    <template #number="{ record }">
                                        <!--
                                                ||：前面为false 返回后面的值，前面为true则返回前面的true
                                                -->
                                        <a-select popup-container="html" class="bacClass" v-model="record.greyCode"
                                            v-if="record.add || record.edit"
                                            style="background-color:#fff; border: 1px solid #c8c8c8; width: 200px;"
                                            @change="changeRecord(record, $event, 1)">
                                            <a-option v-for="item in pageData.gcList" :value="item.greyCode">{{
                                                item.greyCode
                                            }}
                                            </a-option>
                                        </a-select>
                                        <span v-else>{{ record.greyCode }}</span>
                                    </template>
                                    <template #name="{ record }">
                                        <a-select popup-container="html" class="bacClass" v-model="record.greyName"
                                            style="background-color:#fff; border: 1px solid #c8c8c8; width: 200px;"
                                            @change="changeRecord(record, $event, 2)" v-if="record.add || record.edit">
                                            <a-option v-for="item in pageData.gcList" :value="item.grayFabricName">{{
                                                item.grayFabricName
                                            }}
                                            </a-option>
                                        </a-select>
                                        <span v-else>{{ record.greyName }}</span>
                                    </template>
                                    <template #editUnit="{ record }">
                                        <a-select popup-container="html" class="bacClass" v-if="record.edit || record.add"
                                            v-model="record.unit" :loading="loading" @search="searchUnit" @focus="focusunit"
                                            allow-clear allow-search :filter-option="false">
                                            <a-option v-for="item in pageData.unitList as any" :value="item.detailName">
                                                {{ item.detailName }}
                                            </a-option>
                                        </a-select>
                                        <span v-else>{{ record.unit }}</span>
                                    </template>

                                    <template #maxCapacityToday="{ record }">


                                        <a-input-number v-if="record.edit || record.add" v-model="record.maxCapacityToday"
                                            class="input-demo bacClass" :min="0" :max="1000000000" />
                                        <span v-else>
                                            {{ record.maxCapacityToday }}
                                        </span>

                                    </template>
                                    <template #targetCapacity="{ record }">
                                        <a-input-number v-if="record.edit || record.add" v-model="record.targetCapacity"
                                            class="input-demo bacClass" :min="0" :max="1000000000" />
                                        <span v-else>
                                            {{ record.targetCapacity }}
                                        </span>

                                    </template>
                                </a-table>
                            </div>
                        </div>
                    </a-tab-pane>
                </a-tabs>
            </div>
        </a-drawer>
    </pageTabelLayout>
</template>


<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue';
import Toolbar from '@/components/Toolbar.vue';
import { useTableColumn, useTable, usePagination, useRowSelection, useRowKey } from '@/hooks/table';
import { post, get } from '@/api/http'
import { Message, Modal } from '@arco-design/web-vue'
import { } from 'fs';
import axios from 'axios'
import WHService from "@/service/wh";

import { localeText } from '@/api/aggridZw'
import { pagingList } from "@/api/paging";
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'

const whService = new WHService()
const companyList = whService.companyList


//定义TS类型
interface Firm {
    name: string,
    id: number
    greyCode: string,
    grayFabricName: string,
    company: string
}

interface Cloth {
    code: string,
}

interface MachineType {
    "id": number | string
    "code": string,
    "name": string,
    "maxCapacity": string,
    "greyCode": string,
    "greyName": string
    //删除
    "deleteState": number | string | undefined,
    // 作废的状态
    "obsoleteState": number | string | undefined,
}


const rowKey = useRowKey("id");


//查询表单form和select绑定的数据
const queryData = reactive({
    firm: "",
    jqType: "",
    jqName: ""
});

//机台类别form和select绑定的数据
const typeData = reactive({
    types: ''
})

//查询下拉框动态绑定的数据变量
const seachData = reactive({
    jqType: '',
    jqName: '',

})

interface gcTsObj {
    code: string,
    company: string,
    createDate: string,
    createUser: string,
    id: number,
    isActive: boolean,
    remark: string,
    sortIndex: number,
    updateDate: string,
    updateUser: string,
}

//选择工厂下拉框数据
let gc = reactive<gcTsObj[]>([])
gc = JSON.parse(localStorage.getItem('gc') || '{}')


//下拉框和弹窗的数据变量
const pageData = reactive<{
    firmList: [],
    gcList: Firm[];
    unitList: [],
    typeList: Firm[],
    rHeight: any,
    showAdd: boolean,
    sideTitle: string,
    pageLoading: boolean
}>({
    firmList: [],
    gcList: [],
    unitList: [],
    typeList: [],
    showAdd: false,
    rHeight: 0,
    //弹窗的标题
    sideTitle: '新增类型',
    pageLoading: false
});

//第二个表格中的下拉框是否显示或隐藏
const editInput = ref(false)
//第二个表格的修改输入框中的动态绑定数据
const editInputData = reactive({
    code: '',
    //坯布名称
    name: '',

})

function changeRecord(record: any, value: any, i: any) {
    if (i === 1) {
        let tempList = dataList.value.filter((o: any) => {
            return o['greyCode'] == value && record.id != o.id;
        })
        if (tempList.length > 0) {
            Message.warning({
                content: '请选择不同的坯布信息!',
                duration: 2000
            });
            record.greyName = '';
            record.greyCode = '';
            return;
        }
        let list = pageData.gcList.filter((o: any) => {
            return o['greyCode'] == value;
        });
        record.greyName = list[0]['grayFabricName'];
        record.greyId = list[0]['id'];
    } else {

        let tempList = dataList.value.filter((o: any) => {
            return o['greyName'] == value && record.id != o.id;
        })
        if (tempList.length > 0) {
            Message.warning({
                content: '请选择不同的坯布信息!',
                duration: 2000
            });
            record.greyName = '';
            record.greyCode = '';
            return;
        }
        let list = pageData.gcList.filter((o: any) => {
            return o['grayFabricName'] == value
        })
        record.greyCode = list[0]['greyCode'];
        record.greyId = list[0]['id'];

    }
}


//定义第一个表的点击修改时，获取的全局变量id
const record1 = ref(0)
const dataList = ref<any[]>([])
//第一个表格的修改
//record：是点击修改时，得到当前被点击项的对象数据
const editHandler1 = (record: any) => {
    //parseInt : 转整数
    record1.value = parseInt(record.id as string)

    //点击第一个表格的修改弹窗获取第二个表格数据请求
    post({
        url: 'aps/dwMachineCapacity/getMachineCapacityPage',
        data: {
            machineId: record.id,
            page: 1,
            size: 10
        }
    }).then((result: any) => {

        //如果后台返回的状态码为200才能执行后续操作
        if (result.code === 200) {
            dataList.value = result.data.list
        }
    })
    //显示弹窗
    pageData.showAdd = true

}

//第二个表格的修改
const editHandler2 = (record: MachineType) => {

    record["edit"] = true

}

let id = 0;
//第二个表格的新增
const addBtn = () => {
    post({
        url: 'aps/dwMachineCapacity/selectpdGreyInformation'
    }).then((res: any) => {
        if (res.code === 200) {
            pageData.gcList = res.data
        }
    })
    id++;
    dataList.value.push({
        id: 'A' + id,
        machineId: record1,
        machineName: "",
        greyId: "",
        greyName: "",
        greyCode: "",
        unit: "",
        maxCapacityToday: 0,
        targetCapacity: 0,
        add: true
    })

}
//第二个表格的删除

const delBtn = () => {
    if (selectedRowKeys.value.length === 0) {
        Message.error('请先勾选')
        return
    }
    Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
            dataList.value = dataList.value.filter((o: any) => {
                return !selectedRowKeys.value.includes(o['id']);
            })
            let ids = selectedRowKeys.value.filter((o: any) => {
                return !o.toString().startsWith("A")
            });
            if (ids.length > 0) {
                //删除的请求
                post({
                    url: 'aps/dwMachineCapacity/delMachineCapacity',
                    data: ids
                }).then((res: any) => {
                    if (res.code === 200) {
                        Message.success({
                            content: '删除成功',
                            duration: 5000
                        })

                    } else {
                        Message.success({
                            content: '删除失败',
                            duration: 5000
                        })
                    }
                })
            }
        }
    })
};


//表格的列描述信息|
const columns = useTableColumn([
    {
        title: '所属公司',
        dataIndex: 'firm',
        width: 150,
        key: 'firm'
    },
    {
        title: '机台编号',
        // 列信息的标识，对应表格的数据
        dataIndex: 'machineCode',
        key: 'machineCode',
        width: 150,
    },
    {
        title: '机器类型',
        dataIndex: 'machineTypeName',
        width: 150,
        key: 'machineTypeName',
    },
    {
        title: '机器名称',
        dataIndex: 'machineName',
        width: 150,
        key: 'machineName',
    },
    {
        title: '机器产量',
        dataIndex: 'machineNum',
        width: 150,
        key: 'machineNum',
    },
    {
        title: '所属区域',
        dataIndex: 'areaName',
        width: 150,
        key: 'areaName',
    },
    {
        title: '创建人',
        dataIndex: 'createName',
        width: 150,
        key: 'createName',
    },
    {
        title: "创建时间",
        key: "createTime",
        dataIndex: "createTime",
        width: 200,
    },
    {
        title: "修改人",
        key: "updateName",
        dataIndex: "updateName",
        width: 150,
    },
    {
        title: "修改时间",
        key: "updateTime",
        dataIndex: "updateTime",
        width: 200,
    },
    {
        title: "备注",
        key: "remark",
        dataIndex: "remark",
        width: 150,
    },
    {
        title: '操作',
        key: 'id',
        slotName: 'action',
        width: 150,
        fixed: 'right'
    }

]);
let tc: any[] = columns.map((o) => {

    let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed']
    }
    if (o.slotName === 'action') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj["lockPosition"] = "right"
        obj['width'] = '80px'
        obj['cellRenderer'] = {
            // template: `<a-tag color="#ff7d00" style="cursor:pointer" @click="a">修改</a-tag>`,
            template: `<el-button style="color:#165dff;"  type="info" link @click="a">修改</el-button>`,
            setup(props: any) {
                const a = () => {
                    editHandler1(props.params.data)
                }
                return {
                    a
                }
            }

        }
    }

    return obj
})



let a = [{
    showRowGroup: 'hide_def',
    "headerName": "",
    "checkboxSelection": true,
    "headerCheckboxSelection": true,
    "pinned": "left",
    "width": 50,
    resizable: false,
    filter: false,
    sortable: false,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: "left",
}]
tc = a.concat(tc)

const columns2 = useTableColumn([

    {
        title: '坯布编号',
        dataIndex: 'greyCode',
        width: 150,
        key: 'greyCode',
        slotName: 'number'
    },
    {
        title: '坯布名称',
        dataIndex: 'greyName',
        width: 150,
        key: 'greyName',
        slotName: 'name'
    },
    {
        title: '单位',
        dataIndex: 'unit',
        width: 150,
        slotName: 'editUnit',
        key: 'unit',
    },
    {
        title: '最高产能（天）',
        dataIndex: 'maxCapacityToday',
        slotName: 'maxCapacityToday',
        width: 150,
        key: 'maxCapacityToday',
    }, {
        title: '目标产能（天）',
        dataIndex: 'targetCapacity',
        slotName: 'targetCapacity',
        width: 150,
        key: 'targetCapacity',
    },
    {
        title: '操作',
        key: 'id',
        slotName: 'action',
        width: 150,
        fixed: 'right'
    }

]);

//新增修改弹窗动态绑定的数据
const formData = reactive({
    code: '',
    name: '',
    //机台类别
    type: '',
    //机台坐标
    coordinates: '',
    //机台区域
    area: '',
    //创建人
    founder: '',
})

let gsDatas = ref<any[]>([])

onMounted(() => {
    doRefresh()
    pageData.rHeight = document.getElementsByClassName("main-section")[0]?.clientHeight
    //表格的高
    if (pageData.rHeight !== undefined) {
        pageData.rHeight = pageData.rHeight - 200;
        console.log(pageData.rHeight);

    }
    window.addEventListener('resize', () => {
        pageData.rHeight = document.getElementsByClassName("main-section")[0]?.clientHeight

        //表格的高
        if (pageData.rHeight !== undefined) {
            pageData.rHeight = pageData.rHeight - 200;
        }

    })


})

//复选框选中的值
const { selectedRowKeys } = useRowSelection()

//此方法用于表格数据动态渲染
const table = useTable()

//表格的pagination分页的属性配置
const pagination = usePagination(doRefresh);
const total = ref(10);
const page = ref(1);
const size = ref(10);
function PageSize(val: any) {
    pagination.page = val;
    doRefresh();
}

function change1(val: any) {
    pagination.pageSize = val;
    doRefresh();
}
function doRefresh() {
    pageData.pageLoading = true
    updateGridState01()
    //发起分页查询的请求
    post({
        url: 'aps/dwMachine/getMachinePage',
        data: {
            page: pagination.page,
            size: pagination.pageSize,
            firm: queryData.firm,
            machineTypeName: seachData.jqType,
            name: seachData.jqName
        }
    }).then((result: any) => {
        console.log(result);
        //如果后台返回的状态码为200才能执行后续操作
        if (result.code === 200) {
            //将后台返回的分页查询数据传入，这个方法可获取表格的数据dataList,动态渲染表格，表格的data属性动态绑定table.dataList即可实现动态渲染
            table.handleSuccess(result.data.list)
            //result.data.pages：总页数
            //使用这个方法，可以将pagination总页数pageCount改为-当前用户点击查询后台返回的总页数
            //传入完成之后，即可动态绑定表格渲染
            // pagination.setTotalSize(result.data.total);
            gridOption.value.setRowData(result.data.list);
            total.value = result.data.total;
        }
    }).catch(console.log).finally(() => {
        pageData.pageLoading = false
    })
}

//查询
const selectHandler = () => {
    pagination.page = 1
    doRefresh()
}

//导出
const exportBtn = () => {
    if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选');
        return
    } else {
        let idList: any = []
        gridOption.value.getSelectedRows().forEach(function (o: any) {
            idList.push(o['id'])
        })
        //将表头拼接出来
        let head = "<th>所属公司</th><th>机台编号</th><th>机器类型</th><th>机器名称</th><th>机器产量</th><th>所属区域</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>"
        //拿到当前表格数据与勾选的行做筛选

        let nowRow = table.dataList.filter(function (o) {
            return (gridOption.value.getSelectedRows().map((o: any) => { return o.id })).indexOf(o["id"]) !== -1;
        })
        let body = "";
        nowRow.forEach(function (o) {
            body += "<tr><td>" + o["firm"] + "</td>";
            body += "<td>" + o["machineCode"] + "</td>";
            body += "<td>" + o["machineTypeName"] + "</td>";
            body += "<td>" + o["machineName"] + "</td>";
            body += "<td>" + o["machineNum"] + "</td>";
            body += "<td>" + o["areaName"] + "</td>";
            body += "<td>" + o["remark"] + "</td>";
            body += "<td>" + o["createName"] + "</td>";
            body += "<td>" + o["createTime"] + "</td>";
            body += "<td>" + o["updateName"] + "</td>";
            body += "<td>" + o["updateTime"] + "</td>";
            body += "</tr>";
        })
        tableToXlsx(head, '机器产能', body)
        console.log(table)
    }
}

function tableToXlsx(head: any, filename: any, body: any) {
    const uri = 'data:application/vnd.ms-excel;base64,',
        template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`;

    const a = document.createElement('a');
    a.href = uri + window.btoa(unescape(encodeURIComponent(template)));
    a.download = filename;
    a.click();
    document.removeChild(a);
}



// 表格准备事件
const gridOption = ref()
const colState = ref()
const gridReady = (params: any) => {
    gridOption.value = params.api
    colState.value = params.columnApi
}
//弹窗的确认和取消
const sideOk = () => {

    editInput.value = false
    //第二个弹窗新增数据
    const addList = dataList.value.filter((o: any) => {
        return o['add']
    })
    //第二个弹窗修改数据
    const editList = dataList.value.filter((o: any) => {
        return o['edit']
    })
    if (addList.length > 0) {
        addList.map(function (o: any) {
            o["id"] = undefined
            return o;
        });
        post({
            url: 'aps/dwMachineCapacity/addMachineCapacity',
            data: addList
        }).then((res: any) => {
            console.log(res);
            if (res.code === 200) {
                Message.success('新增成功')
                pageData.showAdd = false
            } else {
                Message.error(res.message)
            }


        })

    }
    if (editList.length > 0) {
        //console.log(editList);
        post({
            url: 'aps/dwMachineCapacity/updateMachineCapacity',
            data: editList
        }).then((res: any) => {
            console.log(res);
            if (res.code === 200) {
                pageData.showAdd = false
                Message.success('修改成功')

            }


        })

    }

}


//新增
const addHandler = () => {
    pageData.showAdd = true
    pageData.sideTitle = '新增机器设备维护'
}


//生成条码
//暂时any,后续需要根据后台返回的数据进行类型定义
const GenerateBtn = (record: any) => {
    console.log(1);

}


const headerShow = ref<boolean>(true)
const options = ref<any[]>([]);
const loading = ref(false);
const focusunit = () => {
    getUnitList("")
};
// 单位下拉框
const searchUnit = (value: any) => {
    if (value) {
        loading.value = true;
        getUnitList(value);
        options.value = pageData.unitList;
        loading.value = false;
    } else {
        options.value = []
    }
};
// 单位下拉框
const getUnitList = (val: any) => {
    post({
        url: 'dict/dictTypeDetail/getListByMap',
        data: {
            codeType: 17,
            detailName: val
        }
    }).then(({ code, data }: any) => {
        if (code == 200) {
            pageData.unitList = data;
        } else {
            Message.error({
                content: '查询失败',
                duration: 5000
            })
        }
    });
};
//下拉框得到焦点
const focusSel1 = () => {
    selCxAll1()
}

//下拉框查询
function selCxAll1() {
    // 公司下拉框
    // post({
    //     url: "org/firmGroup/getFirmInfoByMap",
    //     data: {
    //         "firmName": '',
    //         "department": '',
    //     }
    // }).then((result) => {
    //     if (result.code === 200) {
    //         if (result.data.length == 0) {
    //             pageData.firmList = []
    //         } else {
    //             pageData.firmList = result.data;
    //         }
    //     }
    // })
}
const handleChange = (_data: any) => {
    table.handleSuccess(_data);
}
const defaultColDef = {
    sortable: true,
    resizable: true,
    filter: true,
}
const localeText1: any = ref(localeText)
const huiche = () => {
    doRefresh();
}
const pagingList1: any = ref(pagingList)
const { saveGridState: saveGridState01, updateGridState: updateGridState01 } = saveOrUpdateGridState01('MachineCapacity002', gridOption, colState, tc)
const onColumnMoved = () => {
    saveGridState01()
}
const onColumnResized = () => {
    saveGridState01()
}
</script>


<style scoped lang="less">
.addBtn {
    width: 80px;
}

.delBtn {
    width: 80px;
    margin-left: 20px;
}

:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
}

:deep(.ag-cell.ag-cell-first-right-pinned:not(.ag-cell-range-left):not(.ag-cell-range-single-cell)) {
    text-align: center;
}
</style>


